package com.usian.admin.service.impl;

import com.alibaba.fastjson.JSON;
import com.sun.org.apache.bcel.internal.generic.ARRAYLENGTH;
import com.usian.admin.feign.ArticleFeign;
import com.usian.admin.feign.WemediaFeign;
import com.usian.admin.service.AdSensitiveService;
import com.usian.admin.service.AdchannelService;
import com.usian.admin.service.WemediaNewsAutoScanService;
import com.usian.common.aliyun.util.GreenImageScan;
import com.usian.common.aliyun.util.GreenTextScan;
import com.usian.common.fastdfs.FastDFSClient;
import com.usian.model.admin.pojos.AdChannel;
import com.usian.model.admin.pojos.AdSensitive;
import com.usian.model.article.pojos.ApArticle;
import com.usian.model.article.pojos.ApArticleConfig;
import com.usian.model.article.pojos.ApArticleContent;
import com.usian.model.article.pojos.ApAuthor;
import com.usian.model.media.pojos.WmNews;
import com.usian.utils.common.SensitiveWordUtil;
import io.seata.spring.annotation.GlobalTransactional;
import javafx.beans.binding.StringBinding;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.*;

@Service
public class WemediaNewsAutoScanServiceImpl implements WemediaNewsAutoScanService {

    @Autowired
    private WemediaFeign wemediaFeign;
    @Autowired
    private ArticleFeign articleFeign;
    @Autowired
    private AdchannelService adChannelService;
    @Autowired
    private GreenTextScan greenTextScan;
    @Autowired
    private GreenImageScan greenImageScan;
    @Autowired
    private FastDFSClient fastDFSClient;
    @Value("${fileServerUrl}")
    private String fileServerUrl;
    @Autowired
    private AdSensitiveService adSensitiveService;


    @Override
    @GlobalTransactional
    public void autoScanByMediaNewsId(Integer id) {

        //参数校验
        if (id == null){
            return;
        }

        WmNews wmNews = wemediaFeign.findById(id);
        if (wmNews == null){
            return;
        };

        //根据状态决定是否要审核
        if (wmNews.getStatus() == 4){
            return;
        }
        if (wmNews.getStatus() == 8 && wmNews.getPublishTime().getTime() <= System.currentTimeMillis()){
            this.saveArticle(wmNews);
        }

        //审核 阿里云内容安全接口

        if (wmNews.getStatus() == 1){

            Map<String, Object> images = this.handleTextAndImages(wmNews);

            //审核文本
            String textStr = (String) images.get("content");
            boolean textScan = this.handleTextScan(textStr, wmNews);
            if (!textScan){
                return;
            }

            //审核图片
            List<String> imagesList = (List<String>) images.get("images");
            boolean imagesScan = this.handleImagesScan(imagesList, wmNews);
            if (!imagesScan){
                return;
            }

            //审核敏感词
            boolean handleSensitive = this.handleSensitive(textStr, wmNews);
            if (!handleSensitive){
                return;
            }

        }

        //修改wmNews status
        if (wmNews.getPublishTime().getTime() > System.currentTimeMillis()){
            this.updateWmnewStatus(wmNews,(short) 8,"审核通过，待发布");
        }else {
            this.updateWmnewStatus(wmNews,(short) 9,"审核通过，已发布");
        }

        //保存 --> ap_article  ap_article_content  ap_article_config
        this.saveArticle(wmNews);

    }

    /**
     * 匹配敏感词
     *
     * @param content
     * @param wmNews
     * @return
     */
    private boolean handleSensitive(String content,WmNews wmNews){
        boolean flag = false;

        List<AdSensitive> allSensitive = adSensitiveService.findAllSensitive();

        List<String> sensitiveListStr = new ArrayList<>();
        for (AdSensitive adSensitive : allSensitive) {
            sensitiveListStr.add(adSensitive.toString());
        }
        SensitiveWordUtil.initMap(sensitiveListStr);

        Map<String, Integer> stringIntegerMap = SensitiveWordUtil.matchWords(content);
        if (stringIntegerMap.size()==0){
            flag = true;
        }else {
            this.updateWmnewStatus(wmNews,(short) 2,"内容中包含敏感词");
        }

        return flag;
    }

    private Map<String,Object> handleTextAndImages(WmNews wmNews){
        String content = wmNews.getContent();

        StringBuilder stringBuilder = new StringBuilder();
        List<String> imageList = new ArrayList<>();

        List<Map> list = JSON.parseArray(content, Map.class);

        for (Map map : list) {
            if (map.get("type").equals("text")){
                stringBuilder.append(map.get("value"));
            }
            if (map.get("type").equals("image")){
                imageList.add(map.get("value").toString());
            }
        }

        //分离封面图片
        if (wmNews.getImages() != null && wmNews.getType()>0){
            String[] split = wmNews.getImages().split(",");
            imageList.addAll(Arrays.asList(split));
        }

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("content", stringBuilder.toString());
        resultMap.put("images", imageList);
        return resultMap;

    }

    private boolean handleImagesScan(List<String> images,WmNews wmNews){
        if (images == null) {
            return true;
        }
        boolean flag = false;

        try {
            List<byte[]> imageList = new ArrayList<>();
            for (String image : images) {
                String replace = image.replace(fileServerUrl, "");

                String groupName = replace.substring(0, replace.indexOf("/"));
                String groupPath = replace.substring(replace.indexOf("/") + 1);
                byte[] download = fastDFSClient.download(groupName, groupPath);
                imageList.add(download);
            }

            Map map = greenImageScan.imageScan(imageList);
            if (!map.get("suggestion").equals("pass")){
                if (map.get("suggestion").equals("block")){
                    this.updateWmnewStatus(wmNews,(short) 2,"文本核实不通过");
                }
                if (map.get("suggestion").equals("review")){
                    this.updateWmnewStatus(wmNews,(short) 3,"文本核实不确定，建议人工核实");
                }
            }else {
                flag = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return flag;

    }

    private boolean handleTextScan(String content,WmNews wmNews){
        boolean flag = false;
        try {
            Map map = greenTextScan.greeTextScan(content);
            if (!map.get("suggestion").equals("pass")){
                if (map.get("suggestion").equals("block")){
                    this.updateWmnewStatus(wmNews,(short) 2,"文本核实不通过");
                }
                if (map.get("suggestion").equals("review")){
                    this.updateWmnewStatus(wmNews,(short) 3,"文本核实不确定，建议人工核实");
                }
            }else {
                flag = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }

    private void updateWmnewStatus(WmNews wmNews, short status, String msg) {
        wmNews.setStatus(status);
        wmNews.setReason(msg);
        wemediaFeign.updateWmNews(wmNews);
    }

    private void saveArticle(WmNews wmNews){
        //保存 --> ap_article  ap_article_content  ap_article_config

        ApArticle apArticle = new ApArticle();
        apArticle.setTitle(wmNews.getTitle());
        apArticle.setLayout(wmNews.getType());
        apArticle.setImages(wmNews.getImages());
        apArticle.setCreatedTime(new Date());

        Integer userId = wmNews.getUserId();

        ApAuthor apAuthor = articleFeign.findByWmUserId(userId);
        if (apAuthor != null){
            apArticle.setAuthorId(Long.valueOf(apAuthor.getId()));
            apArticle.setAuthorName(apAuthor.getName());
        }

        Integer channelId = wmNews.getChannelId();
        AdChannel adChannel = adChannelService.getById(channelId);
        if (adChannel!=null){
            apArticle.setChannelId(channelId);
            apArticle.setChannelName(adChannel.getName());
        }

        ApArticle apArticle1 = articleFeign.saveApArticle(apArticle);


        ApArticleContent apArticleContent = new ApArticleContent();
        apArticleContent.setArticleId(apArticle.getId());
        apArticleContent.setContent(wmNews.getContent());
        ApArticleContent apArticleContent1 = articleFeign.saveApArticleContent(apArticleContent);


        ApArticleConfig apArticleConfig = new ApArticleConfig();
        apArticleConfig.setArticleId(apArticle.getId());
        apArticleConfig.setIsForward(true);
        apArticleConfig.setIsDelete(false);
        apArticleConfig.setIsDown(true);
        apArticleConfig.setIsComment(true);
        ApArticleConfig apArticleConfig1 = articleFeign.saveApArticleConfig(apArticleConfig);

    }

}
